import 'package:equatable/equatable.dart';
import 'package:website.core/core/domain/entities/web/web_subscription.dart';
import 'package:website.core/core/infrastructure/dtos/api/api_money_amount_dto.dart';
import 'package:website.core/core/infrastructure/dtos/api/api_web_purchase_item_dto.dart';
import 'package:website.core/core/infrastructure/dtos/api/api_web_subscription_duration_dto.dart';

const kApiWebSubscriptionDurationKey = 'duration';

const kApiWebSubscriptionTypeValue = 'subscription';

class ApiWebSubscriptionDto extends Equatable implements ApiWebPurchaseItemDto {
  const ApiWebSubscriptionDto._internal({
    required this.sku,
    required this.priceDto,
    required this.title,
    required this.legacy,
    required this.durationDto,
  });

  @override
  final String sku;

  @override
  final ApiMoneyAmountDto priceDto;

  @override
  final String title;

  @override
  final bool legacy;

  final ApiWebSubscriptionDurationDto durationDto;

  @override
  List<Object?> get props {
    return [
      sku,
      priceDto,
      title,
      legacy,
      durationDto,
    ];
  }

  @override
  String get type => kApiWebSubscriptionTypeValue;

  factory ApiWebSubscriptionDto.fromJson(Map<String, dynamic> json) {
    final priceJson = Map.castFrom<dynamic, dynamic, String, dynamic>(json[kApiWebPurchaseItemPriceKey]);
    final priceDto = ApiMoneyAmountDto.fromJson(priceJson);

    final durationString = json[kApiWebSubscriptionDurationKey] as String;
    final durationDto = ApiWebSubscriptionDurationDto.fromString(durationString);

    return ApiWebSubscriptionDto._internal(
      sku: json[kApiWebPurchaseItemSkuKey],
      priceDto: priceDto,
      title: json[kApiWebPurchaseItemTitleKey],
      legacy: json[kApiWebPurchaseItemLegacyKey],
      durationDto: durationDto,
    );
  }

  @override
  WebSubscription toEntity() {
    return WebSubscription(
      sku: sku,
      price: priceDto.toEntity(),
      title: title,
      legacy: legacy,
      duration: durationDto.toEntity(),
    );
  }
}
